#include "event.h"
#include <algorithm>

using namespace kraw;

EventDispatcher::EventDispatcher()
{
}

EventDispatcher::~EventDispatcher()
{
}

void EventDispatcher::addEventListener(const std::string& type, EventListener* listener)
{
    listeners[type].push_back(listener);
}

void EventDispatcher::dispatchEvent(ObjectEvent* event)
{
    if (!hasEventListener(event->type)) return;
    
    std::vector<EventListener*> elisteners = listeners[event->type];
    
    int size = elisteners.size();
    
    for (int i = 0; i < size; ++i)
        elisteners[i]->onEvent(event);
}

bool EventDispatcher::hasEventListener(const std::string& type)
{
    return listeners.find(type) != listeners.end();
}

void EventDispatcher::removeEventListener(const std::string& type, EventListener* listener)
{
    if (!hasEventListener(type)) return;
    
    std::vector<EventListener*>& elisteners = listeners[type];

    std::vector<EventListener*>::iterator it = find(elisteners.begin(), elisteners.end(), listener);
    
    if (it != elisteners.end())
    {
        elisteners.erase(it);
    }
    
    if (elisteners.size() == 0)
    {
        listeners.erase(type);
    }
}
